<template>
	<div class="up-image thumb" @click="upload">
		<img class="none" v-show="!showValues" src="@/assets/images/add-img.png" />
		<img class="img-value" v-show="showValues" :src="showValues" />
		<img
			class="img-clearable"
			title="删除"
			v-show="clearable && showValues"
			@click.stop="clear"
			src="@/assets/images/img-close.png"
		/>
	</div>
</template>
<script setup lang="ts" name="">
import { fileToBase64Async } from "@/utils/util";
import { ref, watch } from "vue";
import getFile from "@/utils/getFile";
import { ElMessage } from "element-plus";

interface Props {
	value?: string | File;
	showValue?: string;
	clearable?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
	value: "",
	showValue: "",
	clearable: false
});

watch(
	() => props.value,
	newValue => {
		resultValue.value = newValue;
	}
);

watch(
	() => props.showValue,
	newValue => {
		showValues.value = newValue;
	}
);

const emits = defineEmits<{
	(event: "update:value", value: File | undefined): void;
	(event: "update:showValue", value: string): void;
}>();

const showValues = ref<string>(props.showValue);

const resultValue = ref<File | string | undefined>(props.value);

const upload = () => {
	getFile("image", 200, {
		errorResult: (msg: string) => ElMessage.error(msg),
		successResult: (file: File) =>
			fileToBase64Async(file)
				.then(res => {
					showValues.value = res;
					resultValue.value = file;
					emits("update:value", file);
					emits("update:showValue", res);
				})
				.catch(() => {
					ElMessage.error("文件转换成base64失败");
				})
	});
};
const clear = () => {
	showValues.value = "";
	emits("update:value", undefined);
	emits("update:showValue", "");
};

defineExpose({ clear });
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
